﻿// Logger.cpp: 定义应用程序的入口点。
//

#include "Logger.h"
#include <QFileInfo>
#include <QDateTime>
#include <QDir>
//#include <QDebug>
#include "iostream"
#include "CfgRead.h"

#include "spdlog/spdlog.h"
#include "spdlog/cfg/env.h"
#include "spdlog/cfg/argv.h"
#include "spdlog/sinks/daily_file_sink.h"

Logger::Logger()
{
	m_set.debug = 1;
}
static Logger* instance = nullptr;
Logger* Logger::GetInstance()
{
	if (instance == nullptr) {
		instance = new Logger();
	}

	return instance;
}
void Logger::Init()
{
	SetConsoleOutputCP(CP_UTF8);
	CfgRead read;
	read.Init();
	m_set = read.GetLogSetting();
	ClearHistory();
	LoadLoggerModule();
}

void Logger::ClearHistory()
{
	QDir d(m_set.path);
	d.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
	d.setSorting(QDir::Time);
	QFileInfoList loglist = d.entryInfoList({ "*.log" });
	QDateTime current = QDateTime::currentDateTime();
	for (auto& iter : loglist) {
		QDateTime create = iter.birthTime();
		auto sec = create.daysTo(current);
		if (sec > (qint64)m_set.limit) { // 1天
			QFile::remove(iter.filePath());
		}
	}
}

void Logger::LoadLoggerModule()
{
	for (auto& iter : m_set.types) {
		spdlog::daily_logger_mt(iter.toStdString(), (m_set.path + iter + ".log").toStdString(), 0, 0);
		spdlog::get(iter.toStdString())->set_level(spdlog::level::trace);
		spdlog::get(iter.toStdString())->flush_on(spdlog::level::trace);
	}
}

QString Logger::FileName(QString file)
{
	QStringList name = file.split('\\');
	if (name.size() > 1) {
		return name.last();
	} else {
		return file;
	}
}

void Logger::CacheLogString(std::string type, int level, const QString& in, QStringList& args)
{
	QString file = FileName(args.takeFirst());
	args.push_front(file);
	QString str = in;
	int i = 0;
	while (str.indexOf("{}") >= 0 && args.size() > (i)) {
		str.replace(str.indexOf("{}"), 2, args.at(i));
		i++;
	}
	log(level, type, str.toStdString());
}

void Logger::log(int level, std::string type, std::string log)
{
	if (level < m_set.level) {
		return;
	}
	if (spdlog::get(type) != nullptr) {
		spdlog::get(type)->log((spdlog::level::level_enum)level, "{}", log);
	}

	if (m_set.debug == 1) {
		QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
		std::cout << time.toStdString() << log << std::endl;
	}
}

void Logger::AddString(QStringList& list, QString arg)
{
	list.append(arg);
}
void Logger::AddString(QStringList& list, QByteArray arg)
{
	list.append(arg);
}
